package cn.ywang.pattern.proxy.custom;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author BeatificWang
 * @date 2019/3/11 23:33
 */
public class ClassLoader extends java.lang.ClassLoader {

	private File classPathFile;

	public ClassLoader() {
		String classPath = ClassLoader.class.getResource("").getPath();
		this.classPathFile = new File(classPath);
	}


	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		String className = ClassLoader.class.getPackage().getName() + "." + name;
		Class<?> clazz = null;
		if (this.classPathFile != null) {
			File classFile = new File(this.classPathFile, name.replaceAll("\\.", "/") + ".class");
			if (classFile.exists()) {
				FileInputStream inputStream = null;
				ByteArrayOutputStream outputStream = null;
				try {
					inputStream = new FileInputStream(classFile);
					outputStream = new ByteArrayOutputStream();
					byte[] buffer = new byte[1024];
					int len;
					while ((len = inputStream.read(buffer)) != -1) {
						outputStream.write(buffer, 0, len);
					}
					clazz = this.defineClass(className, outputStream.toByteArray(), 0, outputStream.size());
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (null != inputStream) {
						try {
							inputStream.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (null != outputStream) {
						try {
							outputStream.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return clazz;
	}
}
